package com.ywy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ywy.common.rest.Result;
import com.ywy.entity.User;
import com.ywy.mapper.UserMapper;
import com.ywy.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywy.shiro.AccountProfile;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywy
 * @since 2021-12-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("email", user.getEmail())
                .or()
                .eq("username", user.getUsername());
        Integer count = userMapper.selectCount(queryWrapper);

        if(count > 0) {
            return Result.failure("用户已存在");
        }

        User temp = new User();
        temp.setUsername(user.getUsername());
        temp.setPassword(SecureUtil.md5(user.getPassword()));
        temp.setEmail(user.getEmail());
        userMapper.insert(temp);
        return Result.success("注册成功，去登录", null);
    }

    @Override
    public AccountProfile login(String email, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", email));
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        if (user.getStatus() != 1) {
            throw new LockedAccountException("用户被禁用");
        }
        if (!user.getPassword().equals(password)) {
            throw new IncorrectCredentialsException("密码错误");
        }

        // 更新最后登录时间
        user.setLastTime(new Date());
        userMapper.updateById(user);
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        return profile;
    }
}
